/**
 *
 * @param {*} url 地址跳转路径
 * @param {*} params 跳转传参
 * @param {*} type 跳转类型
 */

/**
 * @use  跳转传参获取方式 再onLoad中获取
 * onLoad(options) {
    console.log(
      "options: ",
      JSON.parse(decodeURIComponent(options.data)).title  //解码以及解析JSON字符串
    );
  },
 */
export const useRouter = (url, params = {}, type = "navigateTo") => {
  try {
    if (Object.keys(params).length)
      url = `${url}?data=${encodeURIComponent(JSON.stringify(params))}`;
    if (type == "navigateBack") {
      uni[type]({ delta: url });
    } else {
      uni[type]({ url });
    }
  } catch (error) {
    console.error(error);
  }
};

export function throttle(fn, delay) {
  let timer = null;
  return function () {
    let context = this;
    // 清除上一次的定时器（如果有的话）
    if (timer) {
      clearTimeout(timer);
    }
    // 设置新的定时器，延迟执行函数fn
    timer = setTimeout(function () {
      fn.apply(context, arguments);
    }, delay);
  };
}

export function toFixed(value, len = 2) {

  let str = value + '';

  if (str.indexOf(".") < 0) {
    return value;
  }

  if (len == 1) {
    return Number(str.match(/^\d+(?:\.\d{0,1})?/));
  } else if (len = 2) {
    return Number(str.match(/^\d+(?:\.\d{0,2})?/));
  }

}

export function showModal(title, content) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title,
      content,
      success: async (res) => {
        if (res.confirm) {
          resolve();
        } else {
          reject();
        }
      },
    });
  })
}
